<?php
    namespace app\admin\model;
    use app\common\model\Model;
    use think\Db;
    
//  model 类
    class BatteryGoods extends Model
    {
        const TABLE_NAME = 'battery_list';
        const CACHE_EXPIRE_LEVEL = self::CACHE_EXPIRE_LEVEL_4;

        protected $name = self::TABLE_NAME;

        const FIELDS= 'goods_id,goods_name,goods_sn,goods_type,goods_cate,price,formal_price,stock,goods_sell_num,goods_img,describe,is_show';
        const GOODS_IMAGE_PATH='battery_goods';

        // 修改商品上架状态
        public static function updateGoodsStatus($status=null,$goods_id=null){
            
            return self::commonQuery(self::TABLE_NAME)
                ->where(['goods_id'=>$goods_id])
                ->setField('is_show',$status);
            
        }
       
        // 根据ID获取商品信息
        public static function getGoodsInfoById($id,$field=''){
            if(empty($id)){
                return [];
            }

            if($field == ''){
                $field=self::FIELDS;
            }
            return self::commonQuery(self::TABLE_NAME,self::CACHE_EXPIRE_LEVEL_2)
                ->field($field)->where('goods_id',$id)->find();

        }

        //获取 商品ID
        public static function getGoodsIdByName($name)
        {
            return self::commonQuery(self::TABLE_NAME)
                   ->where(['goods_name'=>'like','%'.$name.'%'])
                   ->column('goods_id');
        }
        // 删除商品
        public static function delGoodsInfo($id){
            // if (!$id) {
            //     return false;
            // }

           return self::commonQuery(self::TABLE_NAME)->where('goods_id',$id)->update(['is_del'=>1]);

        }

       //获取 商品列表
        public static function getGoodsListQuery($good_cate=0){

            $query = self::commonQuery(self::TABLE_NAME)
                    ->field(self::FIELDS)
                   ->where(['is_del'=>0]);

            if($good_cate > 0)
            {
                $query->where(['goods_cate'=>$good_cate]);
            }
            return $query;

        }
        public static function handleGoodsInfo($info,$user_id)
        {
            $info['goods_img']=get_image_url(self::GOODS_IMAGE_PATH,$info['goods_img']);
            
            return $info;
        }
        public static function getGoodsCount($good_cate =0 )
        {
            return self::getGoodsListQuery($good_cate)->count();
        }
        //取消订单时， 添加 库存 和 减少 卖出数
        public static function incrGoodsNum($goods_id,$num)
        {
            return self::commonQuery(self::TABLE_NAME)
                ->where(['goods_id'=>$goods_id])
                ->exp("goods_sell_num","goods_sell_num - $num")
                ->setInc('stock',$num);
        }

      

    }

